/**
 * 
 */
package net.phoenix.repository;

import java.sql.SQLException;
import java.util.List;
import java.util.Vector;

import javax.jcr.RepositoryException;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.nodetype.InvalidNodeTypeDefinitionException;
import javax.jcr.nodetype.NodeType;
import javax.jcr.nodetype.NodeTypeDefinition;
import javax.jcr.nodetype.NodeTypeExistsException;
import javax.jcr.nodetype.NodeTypeIterator;
import javax.jcr.nodetype.NodeTypeManager;
import javax.jcr.nodetype.PropertyDefinition;

import net.phoenix.repository.dao.ValueTableCreateDao;
import net.phoenix.repository.nodetype.BasicNodeTypeIterator;
import net.phoenix.repository.nodetype.NodeTypeManagerWrapper;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author lixf
 * 
 */
public class BasicNodeTypeManager extends NodeTypeManagerWrapper {
	private BasicSession session;
	private static final Log log = LogFactory
			.getLog(BasicNodeTypeManager.class);

	public BasicNodeTypeManager(BasicSession session,
			NodeTypeManager nodeTypeDefinitions) {
		super(nodeTypeDefinitions);
		this.session = session;
	}

	@Override
	public NodeType registerNodeType(final NodeTypeDefinition ntd,
			final boolean updated) throws InvalidNodeTypeDefinitionException,
			NodeTypeExistsException, UnsupportedRepositoryOperationException,
			RepositoryException {
		log.debug("register node type " + ntd.getName() + "...");
		ValueTableCreateDao ntdao = session.getDao(ValueTableCreateDao.class);
		try {
			if (!ntdao.isTableExists(ntd.getName()))
				ntdao.createTable(ntd.getName());

			for (PropertyDefinition definition : ((NodeType) ntd)
					.getPropertyDefinitions()) {
				ntdao.addColumn(ntd.getName(), definition.getName(),
						definition.isMultiple(), definition.isQueryOrderable(),
						definition.getRequiredType());
			}
			log.debug("register node type " + ntd.getName() + " successfully. ");
		} catch (SQLException ex) {
			throw new RepositoryException(ex);
		}

		return (NodeType) ntd;
	}

	@Override
	public NodeTypeIterator registerNodeTypes(NodeTypeDefinition[] ntds,
			boolean allowUpdate) throws InvalidNodeTypeDefinitionException,
			NodeTypeExistsException, UnsupportedRepositoryOperationException,
			RepositoryException {
		List<NodeType> types = new Vector<NodeType>();
		for (int i = 0; i < ntds.length; i++)
			types.add(this.registerNodeType(ntds[i], allowUpdate));
		return new BasicNodeTypeIterator(types);
	}

}
